﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using ShareMarking.Interface;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Data;
using MySoft.Data;

namespace ShareMarking.SyncSFDC
{
    class Program
    {
        static void Main(string[] args)
        {
            string urlstr = ConfigurationManager.AppSettings["urlstr"];
            string client_id = ConfigurationManager.AppSettings["client_id"];
            string client_secret = ConfigurationManager.AppSettings["client_secret"];
            string username = ConfigurationManager.AppSettings["username"];
            string password = ConfigurationManager.AppSettings["password"];
            string grant_type = ConfigurationManager.AppSettings["grant_type"];

            ComLib.LogLib.Log4NetBase.Log("开始同步数据！");
            var sfsync = new SDFC_Sync(urlstr, client_id, client_secret,
                username, password, grant_type);

            #region 同步医院数据
            //SyncHosp(sfsync);//2017-6-12暂停医院同步
            #endregion

            #region 同步PNR数据
            SyncPNR(sfsync);
            //SyncStort();
            #endregion

            #region 同步二维码
            string vigohttp = ConfigurationManager.AppSettings["vigohttp"];
            string signscrect = ConfigurationManager.AppSettings["signscrect"];
            SFDC_QRCode ncqrsync = new SFDC_QRCode(vigohttp, signscrect);

            ComLib.LogLib.Log4NetBase.Log("3、====更新医院二维码========开始====");
            //ncqrsync.Sync_HospQrCode();//2017-6-12暂停医院同步
            ComLib.LogLib.Log4NetBase.Log("3、====更新医院二维码========结束====");

            ComLib.LogLib.Log4NetBase.Log("4、====更新PNR二维码========开始====");
            ncqrsync.Sync_PNRQrCode();///Sync_PNRQrCode2();//批量更新子来源、指定代码
            ComLib.LogLib.Log4NetBase.Log("4、====更新PNR二维码========结束====");
            #endregion
        }

        private static void SyncPNR(SDFC_Sync sfsync)
        {
            try
            {
                var resultentity = sfsync.GetPNR();
                var pnrlist = resultentity.PNRLists;

                ComLib.LogLib.Log4NetBase.Log("2.=========得到PNR列表！数量:" + pnrlist.Count);

                pnrlist.ForEach(o =>
                {
                    ComLib.LogLib.Log4NetBase.Log("2.=========处理PNR！PNRCode:" + o.PNR_EmployeeNumber__c);
                    try
                    {
                        if (o.PNR_EmployeeNumber__c != null && o.PNR_EmployeeNumber__c !="")
                        {
                            if (!sfdc_PNRService.Instance.Get_IsExist_ByWhere(sfdc_PNR._.EmployeeNumber__c == o.PNR_EmployeeNumber__c))
                            {
                                sfdc_PNR hosp = new sfdc_PNR()
                                {
                                    PNRID = o.Id,
                                    EmployeeNumber__c = o.PNR_EmployeeNumber__c,
                                    Region__c = o.PNR_Region__c,
                                    Area__c = o.PNR_Area__c,
                                    DataType__c = o.DataType__c,
                                    Name__c = o.PNR_Name__c,
                                    IsActive__c = o.PNR_IsActive__c,
                                    Sync_Status__c = o.Sync_Status__c,
                                    Sync_Date__c = o.Sync_Date__c,
                                    Status__c = o.Status__c,
                                    isneedupdate = true
                                };
                                sfdc_PNRService.Instance.Add_Entity(hosp);
                                ComLib.LogLib.Log4NetBase.Log("2.2.====新增PNR数据====pnrcode::" + o.PNR_EmployeeNumber__c);
                            }
                            else
                            {
                                #region 修改
                                var pnrent = sfdc_PNRService.Instance.Get_SingleEntity_byWhere(sfdc_PNR._.EmployeeNumber__c == o.PNR_EmployeeNumber__c);
                                pnrent.PNRID = o.Id;
                                pnrent.EmployeeNumber__c = o.PNR_EmployeeNumber__c;
                                pnrent.Region__c = o.PNR_Region__c;
                                pnrent.Area__c = o.PNR_Area__c;
                                pnrent.DataType__c = o.DataType__c;
                                pnrent.Name__c = o.PNR_Name__c;
                                pnrent.IsActive__c = o.PNR_IsActive__c;
                                pnrent.Sync_Status__c = o.Sync_Status__c;
                                pnrent.Sync_Date__c = o.Sync_Date__c;
                                pnrent.Status__c = o.Status__c;
                                pnrent.isneedupdate = true;
                                sfdc_PNRService.Instance.Update_Entity(pnrent);

                                ComLib.LogLib.Log4NetBase.Log("1.1.=========修改一条PNR数据：：pnrcode:" + o.PNR_EmployeeNumber__c);
                                #endregion
                            }
                        }
                        else
                        {
                            ComLib.LogLib.Log4NetBase.Log("2.3.====同步PNR数据异常:PNR_EmployeeNumber__c=null" + "PNRID =" + o.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        ComLib.LogLib.Log4NetBase.Log("2、====同步PNR数据1条====错误=====" + ex.Message + ex.StackTrace);
                    }
                });
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("2、====同步PNR数据====错误=====" + ex.Message + ex.StackTrace);
            }
        }

        private static void SyncHosp(SDFC_Sync sfsync)
        {
            try
            {
                var resultentity = sfsync.GetHosptial();
                var hosplist = resultentity.hospitalLists;
                ComLib.LogLib.Log4NetBase.Log("1.=========得到医院列表！数量：" + hosplist.Count);
                hosplist.ForEach(o =>
                {
                    try
                    {
                        if (o.Hospital_Code__c != null && o.Hospital_Code__c !="")
                        {
                            if (!sfdc_HospitalService.Instance.Get_IsExist_ByWhere(sfdc_Hospital._.Code__c == o.Hospital_Code__c))
                            {
                                #region 新增医院
                                sfdc_Hospital hosp = new sfdc_Hospital()
                                {
                                    HospitalID = o.Id,
                                    Region__c = o.Hospital_Region__c,
                                    Area__c = o.Hospital_Area__c,
                                    DataType__c = o.DataType__c,
                                    MSR_StaffID__c = o.Hospital_MSR_StaffID__c,
                                    Owner__c = o.Hospital_Owner__c,
                                    Code__c = o.Hospital_Code__c,
                                    Name__c = o.Hospital_Name__c,
                                    Active__c = true,//o.Hospital_Active__c, 新增设置为激活
                                    Sync_Status__c = o.Sync_Status__c,
                                    Sync_Date__c = o.Sync_Date__c,
                                    Status__c = o.Status__c,
                                    isneedupdate = true
                                };
                                sfdc_HospitalService.Instance.Add_Entity(hosp);
                                ComLib.LogLib.Log4NetBase.Log("1.1.=========添加一条医院数据：：hospcode:" + o.Hospital_Code__c);
                                #endregion
                            }
                            else
                            {
                                #region 修改
                                var hospent = sfdc_HospitalService.Instance.Get_SingleEntity_byWhere(sfdc_Hospital._.Code__c == o.Hospital_Code__c);

                                hospent.HospitalID = o.Id;
                                hospent.Region__c = o.Hospital_Region__c;
                                hospent.Area__c = o.Hospital_Area__c;
                                hospent.DataType__c = o.DataType__c;
                                hospent.MSR_StaffID__c = o.Hospital_MSR_StaffID__c;
                                hospent.Owner__c = o.Hospital_Owner__c;
                                hospent.Code__c = o.Hospital_Code__c;
                                hospent.Name__c = o.Hospital_Name__c;
                                hospent.Active__c = o.Hospital_Active__c;
                                hospent.Sync_Status__c = o.Sync_Status__c;
                                hospent.Sync_Date__c = o.Sync_Date__c;
                                hospent.Status__c = o.Status__c;
                                hospent.isneedupdate = true;

                                sfdc_HospitalService.Instance.Update_Entity(hospent);


                                ComLib.LogLib.Log4NetBase.Log("1.1.=========修改一条医院数据：：hospcode:" + o.Hospital_Code__c);
                                #endregion
                            }
                        }
                        else 
                        {
                            ComLib.LogLib.Log4NetBase.Log("1.2.====同步医院数据异常:Hospital_Code__c=null" + "HospitalID =" + o.Id);
                        }
                    }
                    catch (Exception ex)
                    {
                        ComLib.LogLib.Log4NetBase.Log("1、====同步医院数据1条====错误=====" + ex.Message + ex.StackTrace);
                    }
                });
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log("1、====同步医院数据====错误=====" + ex.Message + ex.StackTrace);
            }
        }

        //更新门店URL
        private static void SyncStort() {
            int SuccessCount = 0;//起始更新成功条数
            int ErroCount = 0;//起始更新相同条数
            var actlist = qr_StoreService.Instance.Get_Entity_byWhere(qr_Store._.isneedupdate == true, qr_Store._.id.Desc);
            bool result = false;
            for (int i = 0; i < actlist.Count; i++)
            {
                ComLib.LogLib.Log4NetBase.Log("1-2、---------------正在执行第(" + i + ")条数据---------------");
                var act = actlist[i];
                act.A_wxUrl = "https://lhloyalty.otype.com/?shopId=" + act.StoreCode + "$shopName=" + act.S_Name + "";
                result = qr_StoreService.Instance.Update_Entity(act);
                if (result)
                {
                    SuccessCount += 1;
                }
                else
                {
                    ErroCount += 1;
                    ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新失败:" + SuccessCount + "条;失败:" + ErroCount + "条---------------");
                }
            }
            ComLib.LogLib.Log4NetBase.Log("1-3、---------------更新成功:" + SuccessCount + "条;失败:" + ErroCount + "条---------------");


//            #region 检测有异常NC处理（isneedupdate=1）
//            String sql = String.Format(@"select store.[StoreCode]
//      ,store.[S_Name],re.qr_Type,re.qr_CodeID,re.qr_Scene_ID ,re.rel_Code from qr_store store left join qr_QrCodeRelate re
//      on re.rel_Code=store.StoreCode
//      where A_SaCode is null and re.IsDelete=0 and re.qr_Type=1002;");
//            DataTable dt = nc_ncuserService.Instance.db.FromSql(sql).ToTable();
//            if (dt.Rows.Count > 0)
//            {
//                ComLib.LogLib.Log4NetBase.Log("00、==========================更新门店A_wxQrCodeID有" + dt.Rows.Count + "条");
//                #region 循环添加数据
//                for (int i = 0; i < dt.Rows.Count; i++)
//                {
//                    String sql2 = String.Format(@"update qr_store set A_wxQrCodeID='{0}' and A_wxSceneID='{1}'", dt.Rows[i]["qr_CodeID"].ToString(), dt.Rows[i]["qr_Scene_ID"].ToString());
//                    var result = DbSession.Default.FromSql(sql2).ToScalar();
//                    ComLib.LogLib.Log4NetBase.Log("01、==========================处理第" + i + "条异常StoreCode:====StoreCode:" + dt.Rows[i]["StoreCode"].ToString()+"");
//                }
//                #endregion
//            }
//            #endregion
        }

    }
}
